package com.xiaoyu.im.request.flow;

import androidx.annotation.NonNull;

import com.xiaoyu.im.client.IMClient;
import com.xiaoyu.im.datamodel.AppMessage;
import com.xiaoyu.im.request.MessageRequest;

import in.srain.cube.util.general.GeneralUtil;
import in.srain.cube.util.internal.AppCallback;

import static com.xiaoyu.im.datamodel.MessageStatus.SDK_FAILED;
import static com.xiaoyu.im.datamodel.MessageStatus.SUCCESS;

public class BaseSendAction implements FlowAction {

    @Override
    public void exec(MessageRequest request) {
        GeneralUtil.runFromBackgroundToMain(() -> beforeSend(request), messageRequest -> send(messageRequest.getPendingMessage(), new AppCallback<AppMessage>() {
            @Override
            public void onSuccess(@NonNull AppMessage message) {
                request.setSuccessMessage(message);
                request.setStatus(SUCCESS);
                RequestFlow.evolveToNextStatus(request);
            }

            @Override
            public void onError(@NonNull Throwable e) {
                request.setThrowable(e);
                request.setStatus(SDK_FAILED);
                RequestFlow.evolveToNextStatus(request);
            }
        }));
    }

    protected MessageRequest beforeSend(MessageRequest request) {
        return request;
    }

    private void send(AppMessage pendingMessage, AppCallback<AppMessage> callback) {
        IMClient.getInstance().sendMessage(pendingMessage, (success, successMessage, exception) -> {
            if (success) {
                callback.onSuccess(successMessage);
            } else {
                callback.onError(exception);
            }
        });
    }
}
